package com.jiyinit.web.core.activiti.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.activiti.cmd.HistoryProcessInstanceDiagramCmd;
import com.jiyinit.web.core.activiti.dto.LeaveBillRequset;
import com.jiyinit.web.core.activiti.dto.TabLeaveBillInfoRequest;
import com.jiyinit.web.core.activiti.entity.TabLeaveBillInfoEntity;
import com.jiyinit.web.core.activiti.entity.TabLeaveDealMindEntity;
import com.jiyinit.web.core.activiti.service.LeaveBillInfoServiceImpl;
import com.jiyinit.web.core.activiti.service.LeaveDealMindServiceImpl;
import com.jiyinit.web.core.activiti.service.UserMemershipServiceImpl;
import com.jiyinit.web.core.activiti.vo.LeaveDealMindEntity;
import com.jiyinit.web.core.activiti.vo.TabLeaveBillinfoVo;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.util.ExportExcelUtil;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.interceptor.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by user1 on 2018/7/18.
 */
@Controller
@RequestMapping(value = "/statistics")
public class DataStatisticsController {

    /**
     * 日志对象
     */
    private final static Logger logger = LoggerFactory.getLogger(DataStatisticsController.class);

    /**
     * 请假service
     */
    @Resource(name = "leaveBillInfoServiceImpl")
    private LeaveBillInfoServiceImpl leaveService;

    @Resource(name = "leaveDealMindServiceImpl")
    private LeaveDealMindServiceImpl leaveDealMindService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    //工作流相关
    @Resource(name = "processEngine")
    ProcessEngine processEngine;

    @Resource(name = "historyService")
    HistoryService historyService;

    /**
     * 请假统计页面
     * @return
     */
    @RequestMapping(value = "/toLeaveStatistics", method = RequestMethod.GET)
    public String toLeaveStatistics() {
        return "activiti/leaveStatistics";
    }

    /**
     * 查询请假信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getInfoList", method = RequestMethod.POST)
    public ResponseEntity<ResponseDto> getInfoList(HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LeaveBillRequset leaveRequset = new LeaveBillRequset();

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        try {
            if (!Check.isNullStrStrict(startTime)) {
                startTime += " 00:00:00";
                leaveRequset.setLvStartTime(sdf.parse(startTime));
            }
            if (!Check.isNullStrStrict(endTime)) {
                endTime += " 23:59:59";
                leaveRequset.setLvEndTime(sdf.parse(endTime));
            }

            List<TabLeaveBillinfoVo> infoList = leaveService.findLeaveInfoListForExport(leaveRequset);
            if(!Check.isNullCollection(infoList)) {
                return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(infoList), HttpStatus.OK);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 请假详情页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toLeaveDetail")
    public String toLeaveDetail(HttpServletRequest request){
        //,@PathVariable("instanceId") String instanceId
        String instanceId = request.getParameter("instanceId");
        request.setAttribute("instanceId", instanceId);
        return "activiti/leaveDetail";
    }

    /**
     * 我的待办 查询历史处理详情 不需要分页
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findTaskHis")
    public PagingResult findTaskHis(HttpServletRequest request) {
        String instanceId = request.getParameter("instanceId");
        List<LeaveDealMindEntity> dealMindList=new ArrayList<>();
        LeaveDealMindEntity dealMind=null;  //处理意见
        TabLeaveDealMindEntity record=null;
        List<TabLeaveDealMindEntity> mindList=null;
        TabCoreUserEntity user=null;
        List<HistoricTaskInstance> his = historyService .createHistoricTaskInstanceQuery().processInstanceId(instanceId).orderByDueDateNullsLast().asc().list();

        for (HistoricTaskInstance task:his) {
            //查询处理意见
            record=new TabLeaveDealMindEntity();
            dealMind=new LeaveDealMindEntity();
            record.setTaskId(task.getId());
            mindList= leaveDealMindService.findBySelective(record);
            if(mindList.size()>0){
                record=mindList.get(0);
                BeanUtils.copyProperties(record,dealMind);
            }
            //查询处理人
            user= userService.getUserInfoByUserId(Integer.parseInt(task.getAssignee()));
            if(null!=user) {
                dealMind.setTaskUserName(user.getUserName());  //用户名字
            }
            //添加历史信息
            dealMind.setHisTask(task);
            dealMindList.add(dealMind);
        }
        PagingResult result = new PagingResult();
        result.setRows(dealMindList);

        return result;
    }

    /**
     * 查看正在进行中的流程图
     *
     * @param
     * @return
     * @author lishaochuan
     * @create 2017/5/5 11:09
     */
    @RequestMapping(value = "/show")
    public void show(String instanceId, HttpServletResponse response) throws Exception {
        Command<InputStream> cmd = new HistoryProcessInstanceDiagramCmd(instanceId);
        InputStream is = processEngine.getManagementService().executeCommand(cmd);
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("image/png");
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = is.read(b, 0, 1024)) != -1) {
            out.write(b, 0, len);
        }
        out.close();
        is.close();
    }

    /**
     * 导出请假信息
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/exportLeaveInfo", method = RequestMethod.POST)
    public void leaveStatistics(HttpServletResponse response, HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LeaveBillRequset leaveRequset = new LeaveBillRequset();

        String headArrayStr = request.getParameter("headList");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        try {
            if (!Check.isNullStrStrict(startTime)) {
                startTime += " 00:00:00";
                leaveRequset.setLvStartTime(sdf.parse(startTime));
            }
            if (!Check.isNullStrStrict(endTime)) {
                endTime += " 23:59:59";
                leaveRequset.setLvEndTime(sdf.parse(endTime));
            }

            List<TabLeaveBillinfoVo> infoList = leaveService.findLeaveInfoListForExport(leaveRequset);
            String[] headArray = headArrayStr.split(",");
            List<Object[]> dataList = new ArrayList<>(infoList.size());

            for (int i = 0; i < infoList.size(); i++){
                Object[] objs = new Object[headArray.length];
                Date startT = infoList.get(i).getLvStartTime();
                Date endT = infoList.get(i).getLvEndTime();
                Date createT = infoList.get(i).getCreateDate();

                objs[0] = (i + 1);
                objs[1] = infoList.get(i).getUserName();
                objs[2] = infoList.get(i).getOrgName();
                objs[3] = infoList.get(i).getLvTypeName();
                objs[4] = sdf.format(startT);
                objs[5] = sdf.format(endT);
                objs[6] = infoList.get(i).getLinkTel();
                objs[7] = infoList.get(i).getLvHours();
                objs[8] = infoList.get(i).getLvDay();
                objs[9] = sdf.format(createT);
                dataList.add(objs);
            }

            ExportExcelUtil util = new ExportExcelUtil("请假数据统计", headArray, dataList, false, response);
            util.export();
        } catch (Exception e){
            request.setAttribute("isSuccess", "-1");
            e.printStackTrace();
        }
    }
}
